package com.shuai.starter.bootstrap;

import cn.hutool.core.collection.CollectionUtil;
import com.shuai.frame.bootstrap.ProviderBootstrap;
import com.shuai.frame.config.XSRpcApplicationContext;
import com.shuai.frame.server.tcp.VertxTcpServer;
import com.shuai.starter.annotation.EnableXSRpc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Map;

/**
 * @author bxs
 * @version 1.0
 * @Date 2024/7/30
 * EnableRpc注解的增强逻辑
 */
@Slf4j
@Component
public class RpcInitBootstrap implements ImportBeanDefinitionRegistrar {

    /**
     * Spring 初始化时执行，初始化 RPC 框架
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        // 获取 EnableRpc 注解的属性值
        String annotationName = EnableXSRpc.class.getName();
        Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(annotationName);
        if (CollectionUtil.isEmpty(annotationAttributes)) {
            throw new RuntimeException("无法解析注解，请先配置：" + annotationName);
        }
        boolean startRpcServer = (boolean) annotationAttributes.get("startRpcServer");
        XSRpcApplicationContext.init();
        if (startRpcServer) {
            // RPC 框架初始化（配置和注册中心）
            new VertxTcpServer().start(XSRpcApplicationContext.getXSRpConfig().getServerPort());
            log.info("XS-RPC 框架初始化完成");
            return;
        }
        log.info("XS-RPC 框架初始化未启动");
    }
}
